package sample.crawler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.scene.control.TableView;
import sample.enums.MapExecCode;
import sample.model.Company;
import sample.utils.HttpRequestor;
import sample.utils.StringUtils;

import java.util.List;
import java.util.concurrent.Callable;

public class GaodeCallable extends BaseCrawler implements Callable<Integer> {
    protected static Boolean firstRequest = true;
    protected static Integer totalPage = 1;
    protected static final Integer pageSize = 20;

    public GaodeCallable()
    {

    }

    public GaodeCallable(String keywords, List<String> exclusiveWords, String area, Boolean filterTel, TableView<Company> qrTable)
    {
        super.keywords = keywords;
        super.qrTable = qrTable;
        super.exclusiveWords = exclusiveWords;
        super.filterTel = filterTel;

        String[] areas = area.split(",");
        super.area = areas[2] == null ? (areas[1] == null ? areas[0] : areas[1]) : areas[2];
    }

    /**
    　* @description:  api地址
            https://lbs.amap.com/api/webservice/guide/api/search

            https://restapi.amap.com/v3/place/text?key=3ad6adff282cd478c85c743b1f795b80&keywords=减肥&city=北京&offset=20&page=1
    　* @author tina.tao
    　* @date 2019/8/8 15:09
    　*/
    @Override
    public Integer call() {
        Integer code = MapExecCode.COMPLETE.getCode();

        for (int pageNo = 1; pageNo <= totalPage; pageNo++) {
            logger.info("[gaode] start to reqest, keywords:{}, area:{}, pageNo:{}", keywords, area, pageNo);
            if(Thread.interrupted()) {
                code = MapExecCode.STOP.getCode();
                break;
            }

            JSONObject jsonObject = request(pageNo);
            logger.info("[gaode] succeed to request, keywords:{}, area:{}, totalPage:{}", keywords, area, totalPage);
            JSONArray results = jsonObject.getJSONArray("pois");

            if(results == null)
            {
                code = MapExecCode.NODATA.getCode();
                break;
            }
            for (Object o : results) {
                JSONObject target = (JSONObject) o;
                // 过滤排除关键字
                String name = target.getString("name");
                if(StringUtils.contains(name, exclusiveWords)) {
                    continue;
                }
                // 过滤空手机号
                String tel = target.getString("tel");
                if(filterTel && (StringUtils.isEmpty(tel) || "[]".equals(tel))) {
                    continue;
                }

                qrTable.getItems().add(new Company(getIndex() + "", target.getString("tel"), name, target.getString("pname")+target.getString("cityname")+target.getString("adname"), target.getString("address"), target.getString("type"),
                        keywords, "高德", target.getString("location")));

            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                code = MapExecCode.STOP.getCode();
            }
        }
        return code;
    }

    private JSONObject request(Integer pageNo){

        String json = null;
        String url = "https://restapi.amap.com/v3/place/text?key=3ad6adff282cd478c85c743b1f795b80&keywords=" + keywords + "&city=" + area + "&output=json&offset="+pageSize+"&page=" + pageNo;
        try {
            json = new HttpRequestor().doGet(url);
        } catch (Exception e) {
            logger.error("[gaode] send request call exception, url:{}, e:{}", url, e);
            e.printStackTrace();
        }


        JSONObject jsonObject = JSONObject.parseObject(json);

        if(firstRequest) {
            Integer total = jsonObject.getInteger("count");
            if(total == null) {
                totalPage = 0;
            } else {
                totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            }
            logger.info("[gaode] start to reqest, keywords:{}, area:{}, totalPage:{}", keywords, area, totalPage);
            firstRequest = false;
        }
        return jsonObject;
    }

}
